package com.own.business.wechat.official.util;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.own.business.wechat.official.constant.ConstantWechatOfficial;
import com.own.business.wechat.official.model.WechatSignModel;
import com.own.business.wechat.official.propertry.WechatOfficialProperties;
import com.own.component.common.util.encrypt.EncryptUtil;
import com.own.component.store.core.Store;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.UUID;

/**
 * WechatOfficialUtil
 *
 * @author chenxueli
 * @date 2023-09-25 17:35:07
 */
@Slf4j
@Component
public class WechatOfficialUtil {

    private static final String ACCESS_TOKEN_KEY = "wechat:at";
    private static final String JSAPI_TICKET_KEY = "wechat:jsapi:ticket";

    @Resource
    private Store<String> store;

    @Resource
    private WechatOfficialProperties wechatOfficialProperties;

    /**
     * 获取微信的accessToken
     *
     * @return accessToken
     */
    public String getAccessToken() {
        var value = store.value().get(ACCESS_TOKEN_KEY);
        if (StringUtils.isNotBlank(value)) {
            return value;
        }
        var api = ConstantWechatOfficial.Api.GET_ACCESS_TOKEN_API
                .replace(ConstantWechatOfficial.Field.APP_ID, wechatOfficialProperties.getAppId())
                .replace(ConstantWechatOfficial.Field.APP_SECRET, wechatOfficialProperties.getAppSecret());
        var body = HttpRequest.post(api).execute().body();
        log.info("获取微信accessToken返回数据：{}", body);
        var object = JSON.parseObject(body);
        var token = object.getString("access_token");
        // 保存
        store.value().set(ACCESS_TOKEN_KEY, token, Duration.ofSeconds(7100));
        return token;
    }

    /**
     * 获取票据信息
     *
     * @return 票据信息
     */
    public String getJsapiTicket() {
        var value = store.value().get(JSAPI_TICKET_KEY);
        if (StringUtils.isNotBlank(value)) {
            return value;
        }
        var api = ConstantWechatOfficial.Api.GET_JSAPI_TICKET_URL.replace(ConstantWechatOfficial.Field.ACCESS_TOKEN, getAccessToken());
        var body = HttpRequest.post(api).execute().body();
        var object = JSON.parseObject(body);
        var ticket = object.getString("ticket");
        // 保存
        store.value().set(JSAPI_TICKET_KEY, ticket, Duration.ofSeconds(7100));
        return ticket;
    }

    /**
     * 获取分享的签名信息
     *
     * @param url 分享的url
     * @return 签名信息
     */
    public WechatSignModel getShareSign(String url) {
        // 获取ticket
        var ticket = getJsapiTicket();
        // 获取当前时间戳
        long timestamp = System.currentTimeMillis() / 1000;
        // 获取随机字符串
        var str = UUID.randomUUID().toString().replace("-", "");
        // 微信唯一标识appId
        var appId = wechatOfficialProperties.getAppId();
        var content = "jsapi_ticket=" + ticket + "&noncestr=" + str + "&timestamp=" + timestamp + "&url=" + url;
        var signature = EncryptUtil.SHA_1.encrypt(content);
        var model = new WechatSignModel();
        model.setUrl(url);
        model.setTicket(ticket);
        model.setNonceStr(str);
        model.setTimestamp(timestamp);
        model.setSignature(signature);
        model.setAppId(appId);
        return model;
    }

}
